package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilNetwork;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.MenuImg;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Comment;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.bean.base.Topic;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.DiscoveryProductAdapter;
import com.simon.mengkou.ui.adapter.ProductAdapter;
import com.simon.mengkou.ui.adapter.TopicCommentAdapter;
import com.simon.mengkou.ui.base.BaseSocialShareActivity;
import com.simon.mengkou.ui.dialog.ShareDialog;
import com.simon.mengkou.ui.view.HorizontalListView;
import com.simon.mengkou.ui.view.MyGridView;
import com.simon.mengkou.utils.UtilOuer;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiazhenshui on 16/5/31.
 */

public class WebTopicDetailActivity extends BaseSocialShareActivity
        implements PullToRefreshBase.OnRefreshListener2<ListView>{
    WebView mWebView;
    TextView mTvRead;
    TextView mTvLike;
    TextView mTvComment;
    HorizontalListView mMgvGoods;
    LinearLayout mLlGoodsRoot;


    //评论
    @Bind(R.id.comment_id_content)
    EditText mEtContent;
    //评论列表
    @Bind(R.id.common_pulltorefresh_id_list)
    PullToRefreshListView mPtrView;

    private DiscoveryProductAdapter mProductAdapter;
    private TopicCommentAdapter mAdapter;
    private String mMaxId = CstOuer.PAGE.DEFAULT_MAXID;

    private String mUrl;
    private String mTitle;
    private Topic mTopic;
    private boolean mIsFollow = true;
    private String mTopicId;
    private boolean mFavered;
    private int mCommentNum;
    private int mFaverNum;

    private Comment mReplyComment;

    private MenuImg mCollectedMenu;
    private MenuImg mUncollectedMenu;


    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);

        Intent intent = getIntent();
        mTopic = (Topic) intent.getSerializableExtra(CstOuer.KEY.TOPIC);
        if(mTopic != null) {
            mUrl = mTopic.getShareUrl();
            mTitle = mTopic.getTitle();
            mIsFollow = mTopic.isLiked();
            mTopicId = mTopic.getId();
            mFavered = mTopic.isFavered();
            mCommentNum = mTopic.getCommentNum();
            mFaverNum = mTopic.getFaverNum();
        } else {
            mTopicId = intent.getStringExtra(CstOuer.KEY.ID);
        }
    }

    @Override
    protected void initTop() {
        if(mTopic == null) {
            return;
        }

        setTitle(R.string.topic_detail_title);
        //返回
        setNavigation(R.drawable.common_ic_left_nav, new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                }else{
                    finish();
                }

                return false;
            }
        });

        //分享
        MenuImg img = new MenuImg.MenuImgBuilder(this)
                .setTitle(R.string.common_share)
                .setIcon(R.drawable.common_ic_share)
                .setListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        showShareDialog();
                        return false;
                    }
                }).build();

        addMenu(img);

        mCollectedMenu = new MenuImg.MenuImgBuilder(this)
                .setIcon(R.drawable.common_ic_collected)
                .setListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        UtilOuer.toast(WebTopicDetailActivity.this, R.string.topic_detail_uncollection_tips);
                        addMenu(mUncollectedMenu);
                        hideMenu(mCollectedMenu);
                        OuerApplication.mUser.setTopicNum(OuerApplication.mUser.getTopicNum() - 1);
                        OuerDispatcher.sendTopicFollowBroadcast(WebTopicDetailActivity.this, mTopicId);
                        AgnettyFuture future = OuerApplication.mOuerFuture.topicFollow(mTopicId, false, null);
                        attachDestroyFutures(future);
                        return false;
                    }
                }).build();

        mUncollectedMenu = new MenuImg.MenuImgBuilder(this)
                .setIcon(R.drawable.common_ic_uncollected)
                .setListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        UtilOuer.toast(WebTopicDetailActivity.this, R.string.topic_detail_collection_tips);
                        addMenu(mCollectedMenu);
                        hideMenu(mUncollectedMenu);
                        OuerApplication.mUser.setTopicNum(OuerApplication.mUser.getTopicNum() + 1);
                        OuerDispatcher.sendTopicFollowBroadcast(WebTopicDetailActivity.this, mTopicId);
                        AgnettyFuture future = OuerApplication.mOuerFuture.topicFollow(mTopicId, true, null);
                        attachDestroyFutures(future);
                        return false;
                    }
                }).build();


        //重试
        setOnRetryListener(new OnRetryListener() {

            @Override
            public void onRetry() {
                loadUrl(mUrl);
            }
        });
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_web_topic_detail);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
        mPtrView.setTag(false);

        //头部
        View header = LayoutInflater.from(this).inflate(R.layout.layout_web_topic_header, null);
        mWebView = (WebView) header.findViewById(R.id.web_id_webview);
        mTvRead = (TextView)header.findViewById(R.id.topic_id_read);
        mTvLike = (TextView)header.findViewById(R.id.topic_id_like);
        mTvComment = (TextView)header.findViewById(R.id.topic_id_comment);
        mMgvGoods = (HorizontalListView)header.findViewById(R.id.topic_id_goods);
        mLlGoodsRoot = (LinearLayout)header.findViewById(R.id.topic_id_goods_tip);
        mProductAdapter = new DiscoveryProductAdapter(this);
        mMgvGoods.setAdapter(mProductAdapter);

        mPtrView.getRefreshableView().addHeaderView(header);

        mAdapter = new TopicCommentAdapter(this, this);
        mPtrView.setAdapter(mAdapter);

        if(mTopic == null) {
            //返回
            setNavigation(R.drawable.common_ic_left_nav, new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    }else{
                        finish();
                    }

                    return false;
                }
            });

            setOnRetryListener(new OnRetryListener() {
                @Override
                public void onRetry() {
                    getData();
                }
            });

            getData();
        } else {
            setViewData();
        }
    }


    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }

        super.onBackPressed();
    }

    /**
     * @author Zhenshui.xia
     */
    private class CommonWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            super.onProgressChanged(view, progress);

            if(progress == 100) {
                setLoading(false);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if(UtilString.isBlank(mTitle)) {
//                setTitle(title);
            }
        }

    }

    /**
     * @author Zhenshui.xia
     */
    private class CommonWebViewClient extends WebViewClient {

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

        }

        @Override
        public void onPageFinished(WebView view, String url) {

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return OuerDispatcher.localUriLoading(WebTopicDetailActivity.this, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                       SslError error) {
            handler.proceed();
        }

    }

    private void loadUrl(String url) {
        if(UtilNetwork.isNetAvailable(this)) {
            setLoading(true);
            mWebView.loadUrl(url);
        } else {
            setRetry(true);
            UtilOuer.toast(this, R.string.res_string_network_unavaiable);
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.share_id_qq://分享到qq
                shareProduct(SHARE_MEDIA.QQ);
                break;
            case R.id.share_id_wechat://分享到微信
                shareProduct(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.share_id_sina://分享到新浪
                shareProduct(SHARE_MEDIA.SINA);
                break;
            case R.id.share_id_qzone://分享qq空间
                shareProduct(SHARE_MEDIA.QZONE);
                break;
            case R.id.share_id_circle://分享微信朋友圈
                shareProduct(SHARE_MEDIA.WEIXIN_CIRCLE);
                break;
        }
    }

    /**
     * 分享
     * @param platform
     */
    private void shareProduct(SHARE_MEDIA platform) {
        if(mTopic == null) {
            return;
        }

        share(platform, getString(R.string.app_name),
                mTopic.getTitle(), mTopic.getH5(), mTopic.getImage().getUrl());
    }

    /**
     * 显示分享对话框
     */
    public void showShareDialog() {
        ShareDialog dialog = new ShareDialog(this, this);
        dialog.showAtLocation(mWebView, Gravity.CENTER, 0, 0);
    }


    /**
     * 获取话题详情
     */
    private void getData() {
        AgnettyFuture future = OuerApplication.mOuerFuture.topicDetail(mTopicId,
                new OuerFutureListener(this){

                    public void onStart(AgnettyResult result) {
                        setLoading(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);


                            mTopic = (Topic) result.getAttach();
                            mUrl = mTopic.getShareUrl();
                            mTitle = mTopic.getTitle();
                            mIsFollow = mTopic.isLiked();
                            mTopicId = mTopic.getId();
                            mFavered = mTopic.isFavered();
                            mCommentNum = mTopic.getCommentNum();
                            mFaverNum = mTopic.getFaverNum();

                            initTop();


                            setViewData();

                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setRetry(true);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setRetry(true);
                    }
                });

        attachDestroyFutures(future);
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉刷新
        getCommentData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉加载更多
        getCommentData(mMaxId, EDirection.LOADMORE);
    }

    /**
     * 获取评论数据
     * @param maxId
     * @param direction
     */
    private void getCommentData(final String maxId, final int direction) {
        AgnettyFuture future = OuerApplication.mOuerFuture.topicCommentList(
                mTopicId, maxId, CstOuer.PAGE.DEFAULT_MINID, CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(this){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mPtrView.onRefreshComplete();

                        List<Comment> datas = (List<Comment>) result.getAttach();
                        int count = UtilList.getCount(datas);
                        //设置最新的max id
                        if(count != 0) {
                            mMaxId = datas.get(count - 1).getId();
                        }

                        //数据已读取完
                        if(count < CstOuer.PAGE.DEFAULT_SIZE) {
                            mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
                        } else {
                            mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                        }

                        if(direction == EDirection.REFRESH) {
                            mAdapter.setList(datas);
                        } else {
                            mAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        mPtrView.onRefreshComplete();
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        mPtrView.onRefreshComplete();
                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 发送评论
     */
    @OnClick(R.id.comment_id_send)
    public void send() {
        if(UtilString.isBlank(mTopicId)) {
            return;
        }

        String content = mEtContent.getText().toString().trim();
        if(UtilString.isBlank(content)) {
            UtilOuer.toast(this, R.string.share_comment_content_empty);
            return;
        }

        UtilOuer.hideInputManager(this);
        String commentId = mReplyComment == null? null : mReplyComment.getId();
        AgnettyFuture future = OuerApplication.mOuerFuture.topicAddComment(mTopicId, content, commentId,
                new OuerFutureListener(this){
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        mEtContent.setText("");
                        mCommentNum++;
                        mTvComment.setText(UtilOuer.formatNum(WebTopicDetailActivity.this, mCommentNum));

                        if(mReplyComment == null) {
                            UtilOuer.toast(WebTopicDetailActivity.this, R.string.share_comment_success);
                        } else {
                            UtilOuer.toast(WebTopicDetailActivity.this, R.string.share_comment_reply_success);
                        }

                        mEtContent.setHint(R.string.share_comment_content_empty);
                        mReplyComment = null;

                        getCommentData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
                        OuerDispatcher.sendTopicAddCommnetBroadcast(WebTopicDetailActivity.this, mTopicId);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        if(mReplyComment == null) {
                            UtilOuer.showExceptionToast(WebTopicDetailActivity.this,
                                    result, R.string.share_comment_failure);
                        } else {
                            UtilOuer.showExceptionToast(WebTopicDetailActivity.this,
                                    result, R.string.share_comment_reply_success);
                        }
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                });

        attachDestroyFutures(future);
    }

    private void setViewData() {
        //收藏
        if (!mIsFollow) {
            addMenu(mUncollectedMenu);
            hideMenu(mCollectedMenu);
        } else {
            addMenu(mCollectedMenu);
            hideMenu(mUncollectedMenu);
        }

        mTvRead.setText(UtilOuer.formatNum(this, mTopic.getReadNum()));


        mTvComment.setText(UtilOuer.formatNum(this, mCommentNum));
        //点赞
        mTvLike.setText(getString(R.string.topic_detail_like, UtilOuer.formatNum(this, mFaverNum)));
        if(mFavered) {//喜欢
            mTvLike.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.topic_ic_liked, 0, 0);
        } else {//不喜欢
            mTvLike.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.topic_ic_unlike, 0, 0);
        }


        mTvLike.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(!mFavered) {
                    mFavered = true;
                    mFaverNum++;
                    mTvLike.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.topic_ic_liked, 0, 0);

                    mTvLike.setText(UtilOuer.formatNum(WebTopicDetailActivity.this, mFaverNum));
                    AgnettyFuture future = OuerApplication.mOuerFuture.topicFaver(mTopicId, null);
                    attachDestroyFutures(future);
                    OuerDispatcher.sendTopicFaverBroadcast(WebTopicDetailActivity.this, mTopicId);
                }
            }
        });

        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new WebTopicDetailActivity.CommonWebViewClient());
        mWebView.setWebChromeClient(new WebTopicDetailActivity.CommonWebChromeClient());
        loadUrl(mUrl);

        getCommentData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
        relativeGoods();
        postRead(mTopicId, 2);
    }


    public void setReply(Comment comment) {
        mEtContent.setText("");
        mReplyComment = comment;
        mEtContent.setHint(getString(R.string.share_comment_content_reply, comment.getUser().getNick()));
    }


    private void relativeGoods() {
        AgnettyFuture future = OuerApplication.mOuerFuture.topicRelativeGoods(mTopicId,
                new OuerFutureListener(this) {
                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        List<Product> datas = (List<Product>) result.getAttach();
                        if(UtilList.isNotEmpty(datas)) {
                            mMgvGoods.setVisibility(View.VISIBLE);
                            mLlGoodsRoot.setVisibility(View.VISIBLE);
                            mProductAdapter.setList(datas);
                        } else {
                            mMgvGoods.setVisibility(View.GONE);
                            mLlGoodsRoot.setVisibility(View.GONE);
                        }
                    }
                });

        attachDestroyFutures(future);
    }


    private void postRead(String id, int type) {
        AgnettyFuture future = OuerApplication.mOuerFuture.postRead(id, type, null);
        attachDestroyFutures(future);
    }

}
